<?php

namespace Modules\Category\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Modules\Category\Models\Category;
class MenuSeeder extends Seeder
{
    //填充菜单数据
    public function run(): void
    {
        $menus=[
            ['name'=>'用户管理','group'=>'menu','pid'=>0,'level'=>1,'children'=>[
                ['name'=>'用户列表','group'=>'menu','level'=>2],

            ]],
            ['name'=>'分类管理','group'=>'menu','pid'=>0,'level'=>1,'children'=>[
                ['name'=>'分类列表','group'=>'menu','level'=>2],
                ['name'=>'添加','group'=>'menu','level'=>2],
            ]],
            ['name'=>'商品管理','group'=>'menu','pid'=>0,'level'=>1,'children'=>[
                ['name'=>'商品列表','group'=>'menu','level'=>2],
                ['name'=>'添加商品','group'=>'menu','level'=>2],
            ]],

        ];
        foreach($menus as $one){
            // 创建父模型时排除children字段
            $parentData = collect($one)->except('children')->toArray();
            $menu = Category::create($parentData);
            
            // 处理子模型
            if (isset($one['children'])) {
                $childModels = [];
                foreach ($one['children'] as $childData) {
                    // 确保子模型有正确的pid
                    $childData['pid'] = $menu->id;
                    $childModels[] = new Category($childData);
                }
                $menu->children()->saveMany($childModels);
            }
        }
    }
}
